<?php
require_once 'models/discounts.inc';
require_once 'models/orm.inc';
require_once 'models/TCatalogProductModel.inc';

class TMSNomenclatureDiscountItem extends TCandyItem {
	public function GetAmount(TMSProductItem $article = null){
		if ($article)
			return $this->Discount->GetAmount($article);
		foreach ($this->Nomenclature->Articles as $a)
			return $this->Discount->GetAmount($a);
		return 0;
	}
	
	public function Calculate($price, TMSProductItem $article = null){
		if ($article)
			return $this->Discount->Calculate($price,$article);
		foreach ($this->Nomenclature->Articles as $a)
			break;
		if ($a)
			return $this->Discount->Calculate($price,$a);
		return 0;
	}
	
	public function __get($nm){
		$v = parent::__get($nm);
		if (is_null($v))
			return $this->Discount->$nm;
		return $v;		
	}
}

class TMSNomenclatureDiscountIterator extends TIteratorAdapter {
	public function Item() {
		return $this->iterator->Item()->Discount;
	}
}

class TMSNomenclatureDiscountModel extends TCandyModel {
	protected function afterConstruct(){
		$this->_conf_classname_ = 'TMSNomenclatureDiscount';
		$this->_array_id_properties_ = array('Nomenclature','Discount');
	}
	
/**
 * @param object $object
 * @return TCandyItem
 */
	public function WrapObject($object, array &$caller_stack = array()){
		if ($object instanceof $this->_conf_classname_)
			return new TMSNomenclatureDiscountItem($object,$this);
		return parent::WrapObject($object,$caller_stack);
	}
	
	public function NomenclatureDiscounts(IItem $nomenclature, $unwrap = false){		
		$result = $this->GetList(new TListOptions(
					array(
						new TFilterOption('Nomenclature',TConditionType::C_EQUAL,$nomenclature->ItemId())
					)));
		if ($unwrap)
			return new TMSNomenclatureDiscountIterator($result);
		
		return $result;
	}	
}